package pers.dawnyang.config;

import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import org.springframework.web.servlet.view.freemarker.FreeMarkerView;
import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver;

/**
 * FreeMarker配置
 * 
 * @author dawn yang
 * 
 */

// @Configuration
public class FreeMarkerConfig {

  private Log log = LogFactory.getLog(FreeMarkerConfig.class);

  @Bean
  @ConditionalOnMissingBean(name = "freeMarkerViewResolver")
  public FreeMarkerViewResolver freeMarkerViewResolver() {
    FreeMarkerViewResolver resolver = new FreeMarkerViewResolver();
    // 配置Freemarker视图解析器
    resolver.setOrder(1);
    resolver.setSuffix(".html");// 解析后缀为html的
    resolver.setRequestContextAttribute("request"); // 为模板调用时，调用request对象的变量名
    resolver.setContentType("text/html;charset=utf-8");
    resolver.setViewClass(FreeMarkerView.class);
    log.info("init FreeMarkerViewResolver success!!!");
    return resolver;
  }

  @Bean
  @ConditionalOnMissingBean(name = "freeMarkerConfigurer")
  public FreeMarkerConfigurer freeMarkerConfigurer() {
    FreeMarkerConfigurer freeMarkerConfigurer = new FreeMarkerConfigurer();
    freeMarkerConfigurer.setDefaultEncoding("utf-8");
    freeMarkerConfigurer.setTemplateLoaderPath("classpath:/view/");
    Properties prop = new Properties();
    prop.setProperty("template_update_delay", "5");
    prop.setProperty("url_escaping_charset", "UTF-8");
    prop.setProperty("defaultEncoding", "UTF-8");
    prop.setProperty("whitespace_stripping", "true");
    prop.setProperty("boolean_format", "true,false");
    prop.setProperty("number_format", "0.##########");
    prop.setProperty("datetime_format", "yyyy-MM-dd HH:mm:ss");
    prop.setProperty("date_format", "yyyy-MM-dd");
    prop.setProperty("time_format", "HH:mm:ss");
    prop.setProperty("tag_syntax", "square_bracket");
    prop.setProperty("classic_compatible", "true");
    prop.setProperty("template_exception_handler", "ignore");
    prop.setProperty("auto_import", "/common/common.ftl as common");
    freeMarkerConfigurer.setFreemarkerSettings(prop);
    log.info("init FreeMarkerConfigurer success!!!");
    return freeMarkerConfigurer;
  }
}
